import 'package:dss_base/dss_base.dart';
import 'package:dss_base/utils/log_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 一般用作操作之后需要请求网络等操作的界面，如：登录、设置..
abstract class BaseState<T extends StatefulWidget, VM extends BaseViewModel>
    extends State<T> {
  late VM viewModel;

  /// 创建 ViewModel
  VM onCreateViewModel();

  Widget onBuild(BuildContext context);

  bool _isFirstInit = true;

  @override
  void initState() {
    super.initState();
    Log.d('initState() - ${runtimeType.toString()}', tag: 'flutter_page_name');
    viewModel = onCreateViewModel();
    initObservers();
    // 当界面加入之后再去调用获取数据的方法
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (_isFirstInit) {
        initData();
        _isFirstInit = false;
      }
    });
  }

  void _onPageDataChange(){
    setState(() {});
  }

  @override
  void dispose() {
    Log.d('dispose() - ${runtimeType.toString()}', tag: 'flutter_page_name');
    viewModel.removeAllListener(isDispose: true);
    viewModel.removeListener(_onPageDataChange);
    viewModel.dispose();
    super.dispose();
  }

  void initObservers() {
    viewModel.addSafeListener(viewModel.dialogState, (){
      switch (viewModel.dialogState.value) {
        case LoadingDialogState.init:
          break;
        case LoadingDialogState.show:
          showLoadingDialog(context);
          break;
        case LoadingDialogState.hide:
          hideLoadingDialog(context);
          break;
      }
    });
    // 监听 ViewModel 的变化，刷新界面
    viewModel.addListener(_onPageDataChange);
  }

  @override
  Widget build(BuildContext context) {
    return onBuild(context);
  }

  void initData() {}

  /// 对话框 - 显示
  void showLoadingDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) {
        return ScreenUtilX.isLandscape(context)
            ? loadingDialogLand
            : loadingDialog;
      },
    ).then((value) {
    });
  }

  /// 对话框 - 隐藏
  void hideLoadingDialog(BuildContext context) {
    // 检查是否可以返回
    // 个人理解当前是否正在显示对话框，如果显示就调用，不显示就不调用，否则就会退出当前界面
    if (Navigator.of(context).canPop()) {
      Navigator.of(context).pop();
    }
  }

  /// 设置底部导航栏的颜色
  void setSystemColor({bool isBlackText = true, Color? navBarColor}) {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarIconBrightness: isBlackText
            ? Brightness.dark
            : Brightness.light,
        systemNavigationBarColor: navBarColor,
      ),
    );
  }
}
